<template>
  <div class="chooseport">
    <div class="top">
      <img :src="middleImg" class="top_img">
    </div>
    <div class="middle">
      <div class="selector" v-for="(item,index) in content" :key="index">
        <!--未完成ajax时让content的linkname为空，即name: ''，这样点击时会没有反应，在完成ajax后才给正确的值，可以正常跳转页面-->
        <router-link :to="{ name: item.linkname }" @click.native="clickRouterLink(item.linkname)">
          <div class="button" :class="{button1: index === 0,button2: index === 1,button3: index === 2}">
            {{item.button}}
          </div>
        </router-link>
        <span class="text" :class="{text80: index%2 == 0,text90: index%2 == 0}">
          {{item.text}}
        </span>
      </div>
    </div>
    <div class="bottom">
      <router-link :to="{ name: 'login' }">
        <!--没有操作sessionStorage和vuex里的数据，只是跳转到登录页面，然后跳转到授权页面，授权完毕后带参数返回本页面-->
        <div class="text_wrap">
          <span class="text">重新登录</span>
        </div>
      </router-link>
    </div>
    <tip_nochoose :tipfile="BusyError"
                  v-if="isShowBusyErrorTip"
                  @closetip="closeBusyErrorTip($event)"></tip_nochoose>
    <div class="register" v-if="isShowRegister">
      <div class="center">
        <div class="inner">
          <div class="tip_wrap">
            <p class="tip">您是第一次进入本应用，请如实填写相关信息</p>
          </div>
          <div class="input_wrap">
            <p class="text">组织</p>
            <input class="text_input" :class="{input_warn: organization_input_warn}"
                   v-model="organization_input"
                   autocomplete="off" maxlength="30" >
            <p class="text">学院</p>
            <input class="text_input" :class="{input_warn: college_input_warn}"
                   v-model="college_input"
                   autocomplete="off" maxlength="30" >
            <p class="text">学号</p>
            <input class="text_input" :class="{input_warn: studentid_input_warn}"
                   v-model="studentid_input"
                   autocomplete="off" maxlength="30" type="number">
            <p class="text">入学年份</p>
            <select class="year_input" :class="{input_warn: year_input_warn}"
                    v-model="year_input" size="5">
              <option>请选择入学年份</option>
              <option v-for="(item,index) in year_input_select_option" :key="index">{{item}}</option>
            </select>
          </div>
          <div class="button_warp">
            <div class="commit" @click="commitAndRegister()">提交</div>
          </div>
        </div>
      </div>
    </div>
    <tip_loading v-if="isShowTipLoading"></tip_loading>
  </div>
</template>

<script>
import tipNoChoose from '../components/login/tip_nochoose'
import tipLoading from '../components/login/tip_loading'
import middleImg from '../assets/img/pluto-success-1.png'
import YBOpenApi from '../service/YBOpenApi'
import loginService from '../service/login'
import cryptoJs from 'crypto-js'
export default {
  name: 'ChoosePort',
  components: {
    tip_nochoose: tipNoChoose,
    tip_loading: tipLoading
  },
  data () {
    return {
      middleImg: middleImg,
      content: [
        {
          button: '个人',
          text: '学生查看个人的综测情况，上传证明材料等',
          linkname: ''
        },
        {
          button: '组织',
          text: '校级、院级社团组织等学生组织上传比赛、活动等的名单，用于综测证明。',
          linkname: ''
        },
        {
          button: '学院',
          text: '学院端负责审核证明、给分、添加条例等操作。',
          linkname: ''
        }
      ],
      BusyError: [
        {
          title: '正在获取用户信息，请稍后再试',
          content: '若无法正常使用，请尝试重新进入程序或点击底部的重新登录'
        }
      ],
      isShowBusyErrorTip: false,
      isShowTipLoading: false, // 是否显示loading
      isShowRegister: false,
      organization_input: '', // 输入的组织
      college_input: '', // 输入的学院
      studentid_input: '', // 输入的学号
      year_input: '请选择入学年份',
      year_input_select_option: [],
      inputUserInfoResolve: null
    }
  },
  methods: {
    decodeAES256Url (verifyRequest) {
      const key = cryptoJs.enc.Utf8.parse(this.$global.AppSecret) // 十六位十六进制数作为密钥
      const iv = cryptoJs.enc.Utf8.parse(this.$global.AppID) // 十六位十六进制数作为密钥偏移量
      let encryptedHexStr = cryptoJs.enc.Hex.parse(verifyRequest)
      let srcs = cryptoJs.enc.Base64.stringify(encryptedHexStr)
      let decrypt = cryptoJs.AES.decrypt(srcs, key,
        {
          iv: iv,
          mode: cryptoJs.mode.CBC,
          padding: cryptoJs.pad.Pkcs7
        })
      // alert('decrypt = ' + decrypt)
      let decryptedStr = decrypt.toString(cryptoJs.enc.Utf8)
      // alert('decryptedStr = ' + decryptedStr)
      // 解密后的字符串一定是256的长，需要把填充进去的null char剔除
      for (let i = 0; i < decryptedStr.length; i++) {
        if (decryptedStr.charCodeAt(i) === 0) {
          // 实际下标为最后一个下标+1，下标是从0开始的
          verifyRequest = decryptedStr.slice(0, i)
          break
        }
      }
      // verifyRequest = JSON.parse(verifyRequest)
      return JSON.parse(verifyRequest)
    },
    clickRouterLink (info) {
      if (info === '') {
        // alert('ajax尚未完成')
        this.showBusyErrorTip()
      } else {
        // alert('点击了路由，即将要跳转到' + info)
      }
    },
    showBusyErrorTip () {
      this.isShowBusyErrorTip = true
    },
    closeBusyErrorTip () {
      this.isShowBusyErrorTip = false
    },
    showRegister () {
      this.isShowRegister = true
    },
    closeRegister () {
      this.isShowRegister = false
    },
    commitAndRegister () {
      let inputError = this.organization_input_warn || this.college_input_warn || this.studentid_input_warn || this.year_input_warn
      if (inputError === false) {
        // 当三个输入框的输入都不为空时，判断学号是否以入学年份开头，不是的话弹框
        // alert('提交成功')
        if (this.studentid_input.length < 4) {
          alert('学号过短')
          return
        }
        // alert('学号前四位为' + this.studentid_input.slice(0, 4))
        if (this.studentid_input.slice(0, 4) !== this.year_input) {
          alert('正确的学号应以入学年份开头，如：201727010301')
          return
        }
        this.closeRegister()
        this.inputUserInfoResolve({
          // promise结束，返回data
          data: ''
        })
      }
    },
    inputUserInfo () {
      return new Promise((resolve, reject) => {
        this.showRegister()
        for (let i = new Date().getFullYear(), j = 0; i >= 2000; i--, j++) {
          this.year_input_select_option[j] = i
        }
        // 把resolve变成全局变量，在提交成功的时候resolve即可
        this.inputUserInfoResolve = resolve
      })
    }
  },
  computed: {
    organization_input_warn: function () {
      if (this.organization_input === '') {
        return true
      }
      return false
    },
    college_input_warn: function () {
      if (this.college_input === '') {
        return true
      }
      return false
    },
    studentid_input_warn: function () {
      if (this.studentid_input === '') {
        return true
      }
      return false
    },
    year_input_warn: function () {
      if (this.year_input === '请选择入学年份') {
        return true
      }
      return false
    }
  },
  async mounted () {
    // alert('mounted')
    this.isShowTipLoading = true
    let verifyRequest
    try {
      verifyRequest = this.decodeAES256Url(this.$route.query.verify_request)
    } catch (e) {
      alert('解析易班客户端提供的信息时出错，请点击底部的重新登录或重新进入本程序')
      this.isShowTipLoading = false
      return
    }
    // alert('token：' + verifyRequest.visit_oauth.access_token)
    let result = await YBOpenApi.CheckTokenUseful(verifyRequest.visit_oauth.access_token)
    result = result.data
    // alert('通过uid拿到的信息为：' + JSON.stringify(result))
    if (result.status === '404') {
      // 404-授权已过期或不存在，跳转到登录界面
      // alert('授权已过期或不存在，跳转到登录界面')
      this.$router.push({ name: 'login' })
    } else if (result.status === 'error') {
      alert('网站出错，请退出后重新进入应用')
    } else {
      // result.status === '200'，授权有效
      // 如果已经授权完成，拿到token、userid、expires
      let token = result.access_token
      let userid = result.userid
      let expires = result.expire_in
      // 通过token去获取用户信息
      let YBUserResult = await YBOpenApi.getYBUserInfo(token)
      YBUserResult = YBUserResult.data
      // alert('getYBUserInfo拿到的data为' + JSON.stringify(YBUserResult))
      if (YBUserResult.status === 'error') {
        alert('获取用户信息失败，原因：' + YBUserResult.info.msgCN + '，请尝试重新登录或重新进入程序')
        this.isShowTipLoading = false
        return
      }
      YBUserResult = YBUserResult.info
      // 通过userid从后端获取这个帐号管理的社团
      // alert('userid is ' + userid)
      // let OrganizationResult = await loginService.getOrganization(userid)
      // alert('获取的社团为' + OrganizationResult.data)
      let organization = ''
      let collegename = ''
      let studentid = ''
      /* 与后端进行通信，判断该userid是否有collegename学院名、studentid学号、organization组织 */
      let checkUserRegisteredResult = await loginService.checkUserRegistered(userid)
      // 返回的data中有、string:college、string:studentId、string:organization
      if (checkUserRegisteredResult.data === '') {
        // alert('checkUserRegistered后端返回的数据为空')
        // ajax返回为空内容，该userid没有记录
        // 使用Promise阻塞当前线程，等待用户输入完毕后点击确定，resolve Promise，继续执行
        await this.inputUserInfo()
        // alert('用户输入的值为：' + this.college_input + this.studentid_input + this.year_input)
        /* 现在把数据发送给后端 */
        let updateUserRegisterInfoResult = await loginService.updateUserRegisterInfo(userid, this.organization_input, this.studentid_input, this.college_input)
        // alert('updateUserRegisterInfo后端返回的数据为' + JSON.stringify(updateUserRegisterInfoResult.data))
        // 后端返回受影响的行数，如果大于0证明数据插入成功，否则提示退出程序重新进入
        if (updateUserRegisterInfoResult.data <= 0) {
          alert('用户注册失败，可能是由于输入的学号已被使用，请退出程序重新进入')
          this.isShowTipLoading = false
          return
        }
        organization = this.organization_input
        collegename = this.college_input
        studentid = this.studentid_input
      } else {
        // alert('checkUserRegistered后端返回的数据为' + JSON.stringify(checkUserRegisteredResult.data))
        // 如果后端返回的数据不为空，证明该用户已注册，直接从后端读取数据
        organization = checkUserRegisteredResult.data.organization
        collegename = checkUserRegisteredResult.data.college
        studentid = checkUserRegisteredResult.data.studentId
      }
      let loginUser = {
        token: token,
        userid: userid,
        expires: expires,
        username: YBUserResult.yb_username,
        usernick: YBUserResult.yb_usernick,
        sex: YBUserResult.yb_sex,
        money: YBUserResult.yb_money,
        exp: YBUserResult.yb_exp,
        userhead: YBUserResult.yb_userhead,
        schoolid: YBUserResult.yb_schoolid,
        schoolname: YBUserResult.yb_schoolname,
        realname: '萧离',
        collegename: collegename, // 所在学院名称
        classname: '软件工程三班', // 所在班级名称
        enteryear: studentid.slice(0, 4), // 入学年份
        studentid: studentid, // 学号
        examid: '12345678910', // 准考证号
        admissionid: '12345678910', // 录取通知编号
        employid: '10086', // 工号
        // organization: OrganizationResult.data // 该用户管理的组织，通过userid从后端获取
        organization: organization // 该用户管理的组织，通过userid从后端获取
      }
      // alert('loginUser is ' + JSON.stringify(loginUser))
      this.$store.commit('initUser', loginUser)
      sessionStorage.setItem('LoginUser', JSON.stringify(loginUser))
      // 只有ajax完成以后，点击跳转时才有具体路径，才能跳转成功
      this.content[0].linkname = 'stindex'
      this.content[1].linkname = 'index'
      this.content[2].linkname = 'Ewelcome'
      this.isShowTipLoading = false
      // alert('mounted结束')
    }
  }
}
</script>

<style lang="scss" scoped>
.chooseport{
  width: calc(100% - #{px2rem(2)});
  height: calc(100% - #{px2rem(2)});
  border: px2rem(1) solid $background-color;
  background-color: $background-color;
  overflow: auto;
  position: relative;
  .top{
    width: 100%;
    height: px2rem(288);
    /*background-color: red;*/
    text-align: center;
    .top_img {
      width: px2rem(153);
      height: px2rem(184);
      margin: px2rem(49) auto px2rem(55);
      /*border: px2rem(2) solid white;*/
    }
  }
  .middle{
    width: 100%;
    display: flex;
    justify-content: space-around;
    /*background-color: black;*/
    /*border: px2rem(2) solid red;*/
    .selector{
      /*width: px2rem(72);*/
      /*height: px2rem(50);*/
      /*border: px2rem(2) solid red;*/
      flex: 1;
      .button{
        width: px2rem(72);
        height: px2rem(72);
        line-height: px2rem(72);
        border-radius: px2rem(36);
        color: #FFF;
        font-size: px2rem(20);
        text-align: center;
        margin: 0 auto;
        background: -webkit-linear-gradient(to bottom,#FFAAB9, #FF5E7A); /* Safari 5.1 - 6.0 */
        background: -o-linear-gradient(to bottom,#FFAAB9, #FF5E7A); /* Opera 11.1 - 12.0 */
        background: -moz-linear-gradient(to bottom,#FFAAB9, #FF5E7A); /* Firefox 3.6 - 15 */
        background: linear-gradient(to bottom,#FFAAB9, #FF5E7A); /* 标准的语法 */
      }
      .button1{
        background: -webkit-linear-gradient(to bottom,#FFAAB9, #FF5E7A); /* Safari 5.1 - 6.0 */
        background: -o-linear-gradient(to bottom,#FFAAB9, #FF5E7A); /* Opera 11.1 - 12.0 */
        background: -moz-linear-gradient(to bottom,#FFAAB9, #FF5E7A); /* Firefox 3.6 - 15 */
        background: linear-gradient(to bottom,#FFAAB9, #FF5E7A); /* 标准的语法 */
      }
      .button2{
        background: -webkit-linear-gradient(to bottom,#59C2FF, #9D6AE8); /* Safari 5.1 - 6.0 */
        background: -o-linear-gradient(to bottom,#59C2FF, #9D6AE8); /* Opera 11.1 - 12.0 */
        background: -moz-linear-gradient(to bottom,#59C2FF, #9D6AE8); /* Firefox 3.6 - 15 */
        background: linear-gradient(to bottom,#59C2FF, #9D6AE8); /* 标准的语法 */
      }
      .button3{
        background: -webkit-linear-gradient(to bottom,#FCDF75, #FFD027); /* Safari 5.1 - 6.0 */
        background: -o-linear-gradient(to bottom,#FCDF75, #FFD027); /* Opera 11.1 - 12.0 */
        background: -moz-linear-gradient(to bottom,#FCDF75, #FFD027); /* Firefox 3.6 - 15 */
        background: linear-gradient(to bottom,#FCDF75, #FFD027); /* 标准的语法 */
      }
      .text{
        display: block;
        line-height: px2rem(14);
        text-align: center;
        color: $text-color;
        /*color: #BCBFC4;*/
        font-size: px2rem(10);
        margin: px2rem(15) auto 0;
        /*border: px2rem(2) solid black;*/
      }
      .text80{
        width: px2rem(80);
      }
      .text90{
        width: px2rem(90);
      }
    }
  }
  .bottom{
    width: 100%;
    height: px2rem(30);
    position: fixed;
    bottom: 0;
    text-align: center;
    .text_wrap{
      width: px2rem(80);
      height: px2rem(30);
      line-height: px2rem(30);
      border-radius: px2rem(15);
      margin: 0 auto;
      .text{
        font-size: $text-size-normal;
        color: #000;
        text-decoration: underline ;
        font-style: italic;
      }
    }

  }
  .register{
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 11;
    background-color: rgba(38,38,38,0.45);
    .center{
      position: absolute;
      top: 45%;
      left: 50%;
      width: 80%;
      min-height: px2rem(394);
      padding: px2rem(20) 0;
      overflow: auto;
      -webkit-transform: translateX(-50%) translateY(-50%);
      -moz-transform: translateX(-50%) translateY(-50%);
      -ms-transform: translateX(-50%) translateY(-50%);
      transform: translateX(-50%) translateY(-50%);
      background-color: #FFF;
      border-radius: px2rem(30);
      .inner{
        width: 80%;
        height: px2rem(394);
        /*border: px2rem(2) solid black;*/
        margin: 0 auto;
        .tip_wrap{
          /*border: px2rem(2) solid red;*/
          margin: 0 auto;
          width: 100%;
          height: px2rem(50);
          .tip{
            width: 100%;
            line-height: px2rem(25);
            margin-bottom: px2rem(4);
            font-weight: bold;
            font-size: $text-size-imp;
            color: #1270E3;
          }
        }
        .input_wrap{
          /*border: px2rem(2) solid red;*/
          margin: px2rem(10) auto 0;
          width: 100%;
          height: px2rem(280);
          .text{
            width: 100%;
            height: px2rem(20);
            line-height: px2rem(20);
            font-size: $text-size-imp;
            /*border: px2rem(2) solid black;*/
          }
          @mixin input{
            height: px2rem(30);
            line-height: px2rem(30);
            font-size: $text-size-normal;
            margin: px2rem(10) 0;
            padding: 0 px2rem(8);
            border-radius: px2rem(4);
            color: $text-color;
          }
          .text_input{
            width: calc(100% - #{px2rem(16)});
            border: px2rem(1) solid black;
            @include input;
          }
          .year_input{
            width: 100%;
            border: px2rem(1) solid #59C2FF;
            background-color: #FFF;
            @include input;
          }
          .input_warn{
            border: px2rem(1) solid red;
          }
        }
        .button_warp{
          width: 100%;
          height: px2rem(44);
          margin: px2rem(10) auto 0;
          .commit {
            width: px2rem(80);
            height: px2rem(44);
            line-height: px2rem(40);
            margin: 0 auto;
            text-align: center;
            font-size: $text-size-imp;
            color: #FFF;
            border-radius: px2rem(22);
            background: -webkit-linear-gradient(to right,$gradients-color-lightblue, $ui-color-assist-purple); /* Safari 5.1 - 6.0 */
            background: -o-linear-gradient(to right,$gradients-color-lightblue, $ui-color-assist-purple); /* Opera 11.1 - 12.0 */
            background: -moz-linear-gradient(to right,$gradients-color-lightblue, $ui-color-assist-purple); /* Firefox 3.6 - 15 */
            background: linear-gradient(to right,$gradients-color-lightblue, $ui-color-assist-purple); /* 标准的语法 */
          }
        }
       }

    }
  }
}
</style>
